//
//  PALoginViewController.m
//  PAMobileWallet
//
//  Created by Pay_SMP002 on 13-7-3.
//  Copyright (c) 2013年 平安付. All rights reserved.
//

#import "PALoginViewController.h"
#import "PALoginView.h"
#import "PublicDefine.h"
#import "UIColor+Extend.h"

#import "SignEncrypt.h"

#import "PAMobileRegisterViewController.h"
#import "PAHeadPicViewController.h"
#import "PAHomePageViewController.h"
#import "PAPersonalViewController.h"

#import "PADataCenter.h"

#define k_USERNAMEPLIST  @"username.plist"

//static const UInt8 publicKey[] =   "30819F300D06092A864886F70D010101050003818D00308189028181009D3DB22795E9925EC1A5AF4E3B2E83FA8879DA78E6CEF0485983FB48AFA39ADBFC846CC55650FEDA9BD368742680D957FE0F582571F84ADB10643A7F3DCB8576D28B447FCC61D06329FCC8B2F2631DEACC1CB80BEAA6EE95B954CA53FA4FE7483DC09F68D91AA198C75E40C4E87151DC429705247176D245C1E22181510DA6650203010001";

@interface PALoginViewController ()

@end

@implementation PALoginViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){
        loginView = [[PALoginView alloc] initWithFrame:RECT_PHONE];
        loginView.parentController = self;
        loginView.backgroundColor = BGVIEW_COLOR;
        //[self.view addSubview:loginView];
        self.view = loginView;

        loginView.userTF.delegate = self;
        loginView.passTF.delegate = self;
        
        [self.navigationController setNavigationBarHidden:NO];
        
        NSMutableArray * dataArray = [[NSMutableArray alloc] initWithObjects:@"15268675467",@"33890976@qq.com", nil];
        listArray = dataArray;

        if (!userNameArray) {
            userNameArray = [[NSMutableArray alloc] initWithCapacity:10];
        }
        
        CGFloat x, y, w, h;
        
        x = (640-580)/4;  y = HEIGHT_LOGINIMAGE + 4 + 50;  w = 580/2;  h = 100;
        usernameTableView = [[UITableView alloc] initWithFrame:CGRectMake(x,y,w,h) style:UITableViewStylePlain];
        usernameTableView.delegate = self;
        usernameTableView.dataSource = self;
        //usernameTableView.backgroundView = nil;
        usernameTableView.backgroundColor = [UIColor colorWithHexString:@"e0e2e5"];
        usernameTableView.showsHorizontalScrollIndicator = YES;
        usernameTableView.showsVerticalScrollIndicator = YES;
        //setTableView.separatorStyle = UITableViewCellSeparatorStyleNone; //去掉横线
        usernameTableView.separatorColor = [UIColor colorWithHexString:@"c5c8cb"];
        usernameTableView.hidden = YES;
        [self.view addSubview:usernameTableView];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:NOT_LoginSuccess object:nil];
    }
    return self;
}

- (void)loginAction:(NSDictionary *)dic
{
    [[NSUserDefaults standardUserDefaults] setObject:loginView.userTF.text forKey:@"loginViewuserTF"];
    NSMutableDictionary *postingDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [postingDic setObject:@"op_login" forKey:k_operationType];
    [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
}
- (void)registerAction:(id)sender
{
    PAMobileRegisterViewController *mobileRegisterController = [[PAMobileRegisterViewController alloc] initWithNibName:nil bundle:nil];
    mobileRegisterController.parentController = self;
    [mobileRegisterController sendmarkType:1];
    
    PAPersonalViewController *personCenterViewConteroller =[self findPersonCenterViewConteroller];
    [self dismissModalViewControllerAnimated:YES];
    
    [personCenterViewConteroller.navigationController  pushViewController:mobileRegisterController animated:NO];
}

- (void)saveUsername
{
    if( ![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:k_USERNAMEPLIST]]){
		NSMutableArray * userArray = [[NSMutableArray alloc] initWithCapacity:10];
        [userArray addObject:loginView.userTF.text];
        [userArray writeToFile:[self dataFilePath:k_USERNAMEPLIST] atomically:YES];
	}
    else
    {
        NSMutableArray * getUserNameArray = [[NSMutableArray alloc] initWithContentsOfFile:[self dataFilePath:k_USERNAMEPLIST]];
        if (![getUserNameArray containsObject:loginView.userTF.text]) {
            [getUserNameArray addObject:loginView.userTF.text];
            [[NSFileManager defaultManager] removeItemAtPath:[self dataFilePath:k_USERNAMEPLIST] error:nil];
            [getUserNameArray writeToFile:[self dataFilePath:k_USERNAMEPLIST] atomically:YES];
        }
    }
}

- (void)testNext:(id)sender
{
    UIButton * receiveButton = (UIButton *)sender;
    
    int tag = [(UIButton *)sender tag];
    if (tag == 0)
    {
        if (personalViewController == nil)
        {
            personalViewController = [[PAPersonalViewController alloc] initWithNibName:nil bundle:nil];
            personalViewController.parentController = self;
        }
        [self.navigationController pushViewController:personalViewController animated:YES];
    }
    if (tag == 1)
    {
        /*
        if (mobileRegisterController == nil)
        {
            mobileRegisterController = [[PAMobileRegisterViewController alloc] initWithNibName:nil bundle:nil];
            mobileRegisterController.parentController = self;
        }
        [self.navigationController pushViewController:mobileRegisterController animated:YES];
         */
    }
    
    if (tag == 3)
    {
        if (!receiveButton.selected)
        {
            [receiveButton setBackgroundImage:[UIImage imageNamed:@"login_userBTup.png"] forState:UIControlStateNormal];
            receiveButton.selected = !receiveButton.selected;
            
            usernameTableView.hidden = NO;
            
            if (userNameArray && [userNameArray count]>1) {

                loginView.passBackImage.frame = CGRectMake(JULI_LOGINTF, HEIGHT_LOGINIMAGE+4+150, SIZE_LOGINTF.width, SIZE_LOGINTF.height);
                loginView.passTF.frame = CGRectMake(JULI_LOGINTF+71, HEIGHT_LOGINIMAGE+4+150, SIZE_LOGINTF.width-97, SIZE_LOGINTF.height);
                loginView.loginButton.frame = CGRectMake(JULI_LOGINBT, HEIGHT_LOGINIMAGE+4+200+20, SIZE_LOGINbUTTON.width, SIZE_LOGINbUTTON.height);
                loginView.registerButton.frame = CGRectMake(JULI_LOGINBT, HEIGHT_LOGINIMAGE+4+200+20+49+12, SIZE_LOGINbUTTON.width, SIZE_LOGINbUTTON.height);
            }
        }
        else
        {
            [receiveButton setBackgroundImage:[UIImage imageNamed:@"login_userBTdown.png"] forState:UIControlStateNormal];
            receiveButton.selected = !receiveButton.selected;
            
            usernameTableView.hidden = YES;
            
            [self reductionFrame];
        }
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    if( ![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:k_USERNAMEPLIST]]){
		//
	}
    else{
        NSMutableArray * getUserNameArr = [[NSMutableArray alloc] initWithContentsOfFile:[self dataFilePath:k_USERNAMEPLIST]];
        userNameArray = getUserNameArr;
        NSLog(@"-------- %@",getUserNameArr);
    }
    NSString * userTFString = [PADataCenter sharedInstance].selfInfo.baseInfo.phoneNum;
    if (nil == userTFString){
        userTFString = @"";
    }else{
        loginView.userTF.text = userTFString;
    }

    if (userNameArray && [userNameArray count]>1) {
        loginView.userButton.hidden = NO;
        if ([userTFString isEqualToString:@""]) {
            loginView.userTF.text = [userNameArray objectAtIndex:0];
        }
    }else if(userNameArray && [userNameArray count]==1){
        loginView.userButton.hidden = YES;
        loginView.userTF.text = [userNameArray objectAtIndex:0];
    }else{
        loginView.userButton.hidden = YES;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

//获取保存用户名密码的文件
- (NSString *)dataFilePath:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:fileName];
}

#pragma mark - UITextFieldDelegate  methods
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == loginView.userTF) {
        loginView.userBackImage.image = [UIImage imageNamed:@"login_account2.png"];
    }else{
        loginView.passBackImage.image = [UIImage imageNamed:@"login_password2.png"];
    }
    [textField setTextColor:[UIColor blackColor]];
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == loginView.userTF) {
        loginView.userBackImage.image = [UIImage imageNamed:@"login_account.png"];
    }else{
        loginView.passBackImage.image = [UIImage imageNamed:@"login_password.png"];
    }
    [textField setTextColor:[UIColor grayColor]];
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == loginView.passTF && usernameTableView.hidden == NO) {
        usernameTableView.hidden = YES;
        [loginView.userButton setBackgroundImage:[UIImage imageNamed:@"login_userBTdown.png"] forState:UIControlStateNormal];
        loginView.userButton.selected = !loginView.userButton.selected;
        [self reductionFrame];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	if (textField == loginView.userTF)
    {
		[loginView.passTF becomeFirstResponder];
	}
	if (textField == loginView.passTF)
    {
		[loginView.passTF resignFirstResponder];
	}

    usernameTableView.hidden = YES;
    [loginView.userButton setBackgroundImage:[UIImage imageNamed:@"login_userBTdown.png"] forState:UIControlStateNormal];
    loginView.userButton.selected = !loginView.userButton.selected;
    [self reductionFrame];

    return YES;
}
- (void)reductionFrame
{
    loginView.passBackImage.frame = CGRectMake(JULI_LOGINTF, HEIGHT_LOGINIMAGE+4+50, SIZE_LOGINTF.width, SIZE_LOGINTF.height);
    loginView.passTF.frame = CGRectMake(JULI_LOGINTF+71, HEIGHT_LOGINIMAGE+4+50, SIZE_LOGINTF.width-97, SIZE_LOGINTF.height);
    loginView.loginButton.frame = CGRectMake(JULI_LOGINBT, HEIGHT_LOGINIMAGE+4+100+20, SIZE_LOGINbUTTON.width, SIZE_LOGINbUTTON.height);
    loginView.registerButton.frame = CGRectMake(JULI_LOGINBT, HEIGHT_LOGINIMAGE+4+100+20+49+12, SIZE_LOGINbUTTON.width, SIZE_LOGINbUTTON.height);
}
- (void)manipulateRspdic:(NSDictionary *)dictionary
{
    NSLog(@"do nothing");
}

#pragma mark - PANetworkDelegate
- (void)paRequestRespons:(NSDictionary *)responsDic userInfo:(NSDictionary *)userInfo
{
    NSString *op = [responsDic objectForKey:k_operationType];
    if ([op isEqualToString:@"op_login"]) {
        [self saveUsername];

        PADataCenter *dataCenter = [PADataCenter sharedInstance];
        [dataCenter updateLoginInfoDic:responsDic];
        [dataCenter loadCacheForLoginId:dataCenter.selfInfo.baseInfo.account];
        NSMutableDictionary *postingDic = [NSMutableDictionary dictionaryWithDictionary:@{k_operationType:@"op_query_last_payment_info",k_loginId:dataCenter.selfInfo.baseInfo.account,@"pageIndex":[NSNumber numberWithInt:1],@"pageSize":[NSNumber numberWithInt:100]}];
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:personalViewController];

        [personalViewController checkUpOrDown:@"down"];
        
        [self dismissModalViewControllerAnimated:YES];
    }
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
    return [userNameArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    return  100/2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell * cell = [usernameTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (nil == cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    UIView *view_bg = [[UIView alloc]initWithFrame:cell.frame];
    view_bg.backgroundColor = [UIColor colorWithHexString:@"fc9322"];
    cell.selectedBackgroundView = view_bg;
    
    cell.textLabel.textColor = [UIColor colorWithHexString:@"#414146"];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.text = [userNameArray objectAtIndex:indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    loginView.userTF.text = [userNameArray objectAtIndex:indexPath.row];
    usernameTableView.hidden = YES;
    [loginView.userButton setBackgroundImage:[UIImage imageNamed:@"login_userBTdown.png"] forState:UIControlStateNormal];
    loginView.userButton.selected = !loginView.userButton.selected;
    
    [self reductionFrame];
}


@end
